package com.wlyuan.open.domain.service.qifan;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Create by Alibaba Http工具类
 */
@Slf4j
public class HttpUtils {
    //保存获取的Cookie值
    public static List<String> cookie = new ArrayList<>();

    //起帆登录后 吧Cookie放入请求中
    private static void getAndStoreCookiesFromResponse(HttpResponse report) {
        // response植入cookie  Set-Cookie可以有多个
        cookie.clear();
        Header[] ssoResponseHeader = report.getHeaders("Set-Cookie");
        if (ssoResponseHeader != null && ssoResponseHeader.length != 0) {
            for (Header stepHeader : ssoResponseHeader) {
                if (stepHeader != null) {
                    cookie.add(stepHeader.getValue());
                }
            }
        }
    }

    public static String qifandoPost(String url, String jsonParam, String flag) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(5000)// 设置连接请求超时时间
                .setSocketTimeout(5500)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/json");
        if (flag.equals("qifan")) {
            for (String s : cookie) {
                httpPost.setHeader("Cookie", s);
            }
        }
        try {
            // 封装post请求参数
            if (StringUtils.isNotEmpty(jsonParam)) {
                // 为httpPost设置封装好的请求参数

                StringEntity s = new StringEntity(jsonParam, "UTF-8");
                s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                        "application/json"));
                httpPost.setEntity(s);
            }

            if (flag.equals("Login")) {
                HttpResponse report = httpClient.execute(httpPost);
                getAndStoreCookiesFromResponse(report);
                // 从响应对象中获取响应内容
                HttpEntity entity = report.getEntity();
                result = EntityUtils.toString(entity);
            } else {
                // httpClient对象执行post请求,并返回响应参数对象
                httpResponse = httpClient.execute(httpPost);
                // 从响应对象中获取响应内容
                HttpEntity entity = httpResponse.getEntity();
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            logger.error("起帆请求异常", e);
        } finally {

            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    logger.error("起帆请求异常", e);
                    logger.error("qifandoPost失败：" + e.getMessage());
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("起帆请求异常", e);
                    logger.error("qifandoPost失败：" + e.getMessage());
                }
            }
        }
        return result;
    }

}
